#pragma once
#include "log.hpp"
#include "Sock.hpp"
#include <sys/epoll.h>
#include "TcpServer.hpp"

class Epoller
{
    static const int gsize = 128;

public:
    static int CreateEpoller()
    {
        int epfd = epoll_create(gsize);
        if (epfd < 0)
        {
            Log(FATAL, "%d : %s", errno, strerror(errno));
            exit(1);
        }
        return epfd;
    }

    static bool DelEvent(int epfd, int sock)
    {
        int n = epoll_ctl(epfd, EPOLL_CTL_DEL, sock, nullptr);
        return n == 0;
    }

    static bool ModEvent(int epfd, int sock, uint32_t event)
    {
        epoll_event ev;
        ev.data.fd = sock;
        ev.events = event;
        int n = epoll_ctl(epfd, EPOLL_CTL_MOD, sock, &ev);
        return n == 0;
    }
    static bool AddToEpoll(int epfd, int sock, uint32_t event)
    {
        epoll_event ev;
        ev.data.fd = sock;
        ev.events = event;
        int n = epoll_ctl(epfd, EPOLL_CTL_ADD, sock, &ev);
        return 0 == n;
    }

    static int LoopOnce(int epfd, epoll_event *revent, int size)
    {
        int n = epoll_wait(epfd, revent, size, 1000);
        if (n == -1)
        {
            Log(FATAL, "epoll_wait: %d:%s", errno, strerror(errno));
        }
        return n;
    }
};
